// 引入net模块
const net = require('net')
// 引入fs/promises模块
const fs = require('fs/promises')
const path = require('path')

// 定义移动光标函数
const moveCursor = (dx, dy) => {
  // 返回一个Promise对象
  return new Promise((resolve) => {
    // 移动光标
    process.stdout.moveCursor(dx, dy, () => {
      // 解析Promise
      resolve()
    })
  })
}

// 定义清除行函数
const clearLine = (dir) => {
  // 返回一个Promise对象
  return new Promise((resolve) => {
    // 清除行
    process.stdout.clearLine(dir, () => {
      // 解析Promise
      resolve()
    })
  })
}

// 创建一个TCP连接
const socket = net.createConnection({ port: 5099, host: '::1' }, async () => {
  const inputPath = process.argv[2]
  const fileName = path.basename(inputPath)
  const fileSize = (await fs.stat(inputPath)).size
  console.log(`开始上传文件：${fileName}，大小：${fileSize}字节`)

  let bytesUploaded = 0
  let uploadedPercentage = 0

  socket.write(`fileName: ${fileName}------`)

  // 打开text.txt文件
  const fileHandler = await fs.open(inputPath, 'r')
  // 创建一个可读流
  const fileReadStream = fileHandler.createReadStream()

  // 监听data事件
  fileReadStream.on('data', (data) => {
    // 如果socket.write返回false，则暂停可读流
    if (!socket.write(data)) {
      fileReadStream.pause()
    }

    bytesUploaded += data.length
    let newPercentage = Math.floor((bytesUploaded / fileSize) * 100)

    if (newPercentage !== uploadedPercentage) {
      uploadedPercentage = newPercentage
      moveCursor(0, -1)
      clearLine(0)
      console.log(`已上传：${bytesUploaded}字节，进度：${uploadedPercentage}%`)
    }
  })

  // 监听drain事件
  socket.on('drain', () => {
    // 当socket.write返回true时，恢复可读流
    fileReadStream.resume()
  })

  // 监听end事件
  fileReadStream.on('end', () => {
    // 当可读流结束时，关闭socket连接
    socket.end()
    fileReadStream.close()
    fileHandler.close()
  })
})
